import { exec } from 'child_process'
import ora from 'ora'
import { Client } from 'ssh2'
import clientScp2 from 'scp2'
import chalk from 'chalk'
import { loadEnv } from 'vite'

const spinner = ora('正在构建项目...').start()
spinner.stopAndPersist({
  text:
    ' __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ \n' +
    ' |                                                          |\n' +
    ' |                    *** 运行发布流程 ***                  |\n' +
    ' |                       【国产化医疗】                     |\n' +
    ' | __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ |\n'
})

spinner.start()
let speed = 20
let time = 20
const count = 400
const getProgress = () => {
  const done = '█'
  const undone = '░'
  let progress = Math.floor((speed / count) * 50)
  if (progress > 50) {
    progress = 50
  }
  const progressBar = done.repeat(progress) + undone.repeat(50 - progress)
  return progressBar
}
const interval = setInterval(() => {
  spinner.text = `正在构建项目 ${getProgress()} 进度${((speed / count) * 100).toFixed(1)}% 耗时${(time / 10).toFixed(1)}秒 `
  speed++
  time++
  if (speed > count) {
    speed = 400
  }
}, 100)
const env = loadEnv('', process.cwd())

// 项目构建
exec('vite build', (error, stdout, stderr) => {
  if (error) {
    spinner.fail(stderr)
    spinner.stop()
    process.exit(0)
  }
  spinner.succeed(stdout)
  // spinner.warn(stderr)
  clearInterval(interval)
  spinner.succeed(chalk.green('项目构建成功'))
  updateFiles()
})
const updateFiles = () => {
  spinner.text = '正在链接服务器...'
  const config = {
    host: env.VITE_HOST,
    port: env.VITE_POST,
    username: env.VITE_USERNAME,
    password: env.VITE_PASSWORD
  }
  // 创建SSH连接
  const connection = new Client()
  // 监听ready事件
  connection
    .on('ready', () => {
      spinner.succeed(chalk.green('服务器链接成功'))
      spinner.text = '正在上传文件...'
      clientScp2.scp(
        'dist',
        {
          ...config,
          path: '/web/his/dev'
        },
        (err) => {
          err ? spinner.fail(err) : spinner.succeed(chalk.green(`🎊 DEV  发布成功，访问 http://${config.host}:8100`))
          spinner.stop()
        }
      )
      clientScp2.scp(
        'dist',
        {
          ...config,
          path: '/home/fudansoft-6100/fudansoft-his-web/'
        },
        (err) => {
          err ? spinner.fail(err) : spinner.succeed(chalk.green(`🎊 PROD 发布成功，访问 http://${config.host}:6100`))
          spinner.stop()
          connection.end()
          //退出
          setTimeout(() => {
            process.exit(0)
          }, 1000)
        }
      )
    })
    .connect(config)

  // 监听error事件
  connection.on('error', (err) => {
    console.error('SSH连接失败', err)
  })
}
